package com.android.task6;

import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

public class ContactSharing extends Activity {
	private Button showQRCodeButton;
	private Button readQRCodeButton;
	private Button exitButton;
	private Button requestContactButton;
	private Button pickContactButton;
	String displayName;
	Context myContext;
	String myMACcAddress;
	String serverMACAddress;
	String clientMACAddress;
	
	Contact contactToBeSent;
	ContactManager contactManager;

	public final static int CONTACT_READ = 1;
	public final static int CONTACT_WRITE = 2;
	public final static int MESSAGE_STATE_CHANGE = 3;
	public final static int MESSAGE_TOAST = 4;
	public final static int PICK_CONTACT = 4;
	
	BluetoothClient bluetoothClient;
	BluetoothServer bluetoothServer;
	ContactSharing activity;
	// Intent request codes
    private static final int REQUEST_ENABLE_BT = 2;
	private static final String TAG = "ContactSharing";
    public static final String TOAST = "toast";

	 // Local Bluetooth adapter
   private BluetoothAdapter mBluetoothAdapter = null;
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
//        initializeService();
        activity = this;
        myContext = this;
        showQRCodeButton = (Button) findViewById(R.id.show_QR_code_button);
        showQRCodeButton.setOnClickListener(showQRCodeButtonListener);
        
        readQRCodeButton = (Button) findViewById(R.id.read_QR_code_button);
        readQRCodeButton.setOnClickListener(readQRCodeButtonListener);
        
        exitButton = (Button) findViewById(R.id.exit_button);
        exitButton.setOnClickListener(exitButtonListener);
        
        requestContactButton = (Button) findViewById(R.id.request_contact_button);
        requestContactButton.setOnClickListener(requestContactButtonListener);
        requestContactButton.setClickable(false);
        
        pickContactButton = (Button) findViewById(R.id.pick_contact_button);
        pickContactButton.setOnClickListener(pickContactListener);
        
        contactManager = new ContactManager(getContentResolver());
        
         // Get local Bluetooth adapter
        mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

        // If the adapter is null, then Bluetooth is not supported
        if (mBluetoothAdapter == null) {
            Toast.makeText(this, "Bluetooth is not available", Toast.LENGTH_LONG).show();
            finish();
            return;
        }
        else {
        	myMACcAddress = mBluetoothAdapter.getAddress();
        	Toast.makeText(this, myMACcAddress, Toast.LENGTH_LONG );
             // If BT is not on, request that it be enabled.
             // setupChat() will then be called during onActivityResult
             if (!mBluetoothAdapter.isEnabled()) {
                 Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                 startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
             // Otherwise, setup the chat session
             } else {
//                 if (mBluetoothManager == null) {
//                 	setupBluetooth();
//
//                 }
             }
        }
        
    }
    
    private OnClickListener pickContactListener = new OnClickListener(){
    	public void onClick(View v) {
    		 Intent i = new Intent(Intent.ACTION_PICK,
    				 ContactsContract.Contacts.CONTENT_URI);
    		 startActivityForResult(i, PICK_CONTACT);
    	}
    };
    
    private OnClickListener requestContactButtonListener = new OnClickListener() {
    	public void onClick(View v){
    		
    		Log.i("MAC: ",serverMACAddress);
    		
    		if(serverMACAddress == null || serverMACAddress == ""){
    			Toast.makeText(myContext, "MAC address not received", Toast.LENGTH_SHORT);
    		}
    		else{
//    		mBluetoothManager.connect(serverMACAddress);
    			
    			bluetoothClient = new BluetoothClient(mBluetoothAdapter,contactManager,serverMACAddress);
    			contactManager.setActivity(activity);
    		}
    	}
    };
    
    private OnClickListener showQRCodeButtonListener = new OnClickListener() {
    	
    	public void onClick(View v){

    		encodeBarcode("TEXT_TYPE",myMACcAddress);
    	}
    };
    
    private OnClickListener readQRCodeButtonListener = new OnClickListener() {
    	public void onClick(View v){
    		 Intent intent = new Intent("com.google.zxing.client.android.SCAN");
    	        intent.putExtra("SCAN_MODE", "QR_CODE_MODE");
    	        startActivityForResult(intent, 0);
    	}
    };
    private OnClickListener exitButtonListener = new OnClickListener() {
    	public void onClick(View v){
    		System.exit(0);
    	}
    };
    
    private void encodeBarcode(String type, String data) {
        Intent intent = new Intent("com.google.zxing.client.android.ENCODE");
        intent.putExtra("ENCODE_TYPE", type);
        intent.putExtra("ENCODE_DATA", data);
        startActivity(intent);
        
        
      }
    @Override
    public synchronized void onResume() {
        super.onResume();
    }

    public void onActivityResult(int requestCode, int resultCode, Intent intent) {
    	
    	switch(requestCode){
    	case 0:
    		if (resultCode == RESULT_OK) {
                String contents = intent.getStringExtra("SCAN_RESULT");
                String format = intent.getStringExtra("SCAN_RESULT_FORMAT");
                // TODO: Handle successful scan
                showDialog(R.string.new_contact, "Format: " + format + "\nContents: " + contents);
               
                serverMACAddress = contents;
                requestContactButton.setClickable(true);
               
            } else if (resultCode == RESULT_CANCELED) {
            	showDialog(R.string.new_contact, "Reading QR code unsuccesfull!");

            }
    		break;
    		
    	case PICK_CONTACT:
    		Cursor c = getContact(intent.getData());
            if (c.moveToFirst())
            {
                String name = c.getString(c.getColumnIndexOrThrow(ContactsContract.Contacts.DISPLAY_NAME));
                System.out.println(name); 
                Toast.makeText(this, name, Toast.LENGTH_SHORT);
                showDialog(R.string.new_contact, "Contact: " + name);
                
                contactToBeSent = contactManager.getContact(name);
                
                bluetoothServer = new BluetoothServer(contactToBeSent,mBluetoothAdapter,activity);
                
          	}
    		break;
    	case REQUEST_ENABLE_BT:
    		// When the request to enable Bluetooth returns
            if (resultCode == Activity.RESULT_OK) {
                // Bluetooth is now enabled
            } else {
                // User did not enable Bluetooth or an error occured
                Log.d(TAG, "BT not enabled");
                Toast.makeText(this, "Bluetooth is not enabled", Toast.LENGTH_SHORT).show();
                finish();
            }
    		break;
    	}
    }  
    private Cursor getContact(Uri uri) {
        // Run query
    	Cursor c =  managedQuery(uri, null, null, null, null);
    	return c;

} 

    public Contact getContactFromList(){
    	Intent i = new Intent(Intent.ACTION_PICK,
    			ContactsContract.Contacts.CONTENT_URI);
    	startActivityForResult(i, PICK_CONTACT);
    	
    	Contact tmpContact = contactToBeSent;
    	contactToBeSent = null;
    	
    	return tmpContact;
    	
    }
    
    public void showDialog(int title, String message) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle(title);
        builder.setMessage(message);
        builder.setPositiveButton("OK", null);
        builder.show();
      }
    
}